package com.servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bean.PayMessage;
import com.config.WeChatConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ophiux.wechat.db.MchAppModel;
import com.ophiux.wechat.db.Mch_App_Map;
import com.ophiux.wechat.utils.Sha1Util;

public class WeChatOauth extends HttpServlet {
	private static Logger logger = LoggerFactory.getLogger(WeChatOauth.class);
	 /**
	 * 文件名称: WeChatOauth
	 * 内容摘要: oauth2 网页授权
	 * 创 建 人: zengjian
	 * 创建日期:2016-5-16
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setHeader("Content-type", "text/html;charset=UTF-8"); 
		response.setCharacterEncoding("utf-8");
		//投递参数
		String userId="";
		String orderNo="";
		String money="";
		String subMchid="";
		String notifyUrl="";
		String backurl="";
		String sign="";
		Map<String, String[]> params = request.getParameterMap();
		for (String key : params.keySet()) {
			String[] values = params.get(key);
			for (int i = 0; i < values.length; i++) {
				String value = values[i];
				if(key.equals("userId")){
					userId=value;
				}else if(key.equals("orderNo")){
					orderNo=value;
				}else if(key.equals("money")){
					money=value;
				}else if(key.equals("subMchid")){
					subMchid=value;
				}else if(key.equals("notifyUrl")){
					notifyUrl=value;
				}else if(key.equals("backurl")){
					backurl=value;
				}else if(key.equals("sign")){
					sign=value;
				}
			}
		}
		 
		 /**
		  * 商户信息,根据MchId获取
		  */
		 MchAppModel mchModel = Mch_App_Map.getMchAppModelByMchId(subMchid);
		 
		 String appid = null;
	     String appsecret = null;
	     String api_key = null;
	     /**
	      * 商户信息存在
	      */
	     if(mchModel != null){
			 appid = mchModel.getAppid();
			 appsecret = mchModel.getAppsecret();
			 api_key = mchModel.getApi_key();
		 }
	     String backUri = WeChatConfig.REDIRECT_URL;
		logger.info("---------------------普通商户:前端传入参数-用作后续的授权获取预支付参数------------------------------");
	    logger.info("userId="+userId
	    		 +"---orderNo="+orderNo
	    		 +"---money="+money
	    		 +"---subMchid="+subMchid
	    		 +"---notifyUrl="+notifyUrl
	    		 +"---backurl="+backurl
	    		 +"---backurl="+appid
	    		 +"---appsecret="+appsecret
	    		 +"---REDIRECT_URL="+backUri
	    		 );
	    logger.info("----------------------普通商户:前端传入参数-用作后续的授权获取预支付参数-----------------------------");
	
	    //共账号及商户相关参数
		
		backUri = backUri+"?userId="+userId+"&orderNo="+orderNo+"&money="+money+"&subMchid="+subMchid+"&notifyUrl="+notifyUrl+"&backurl="+ URLEncoder.encode(backurl,"utf-8")+"";
		backUri = URLEncoder.encode(backUri,"utf-8");
		//授权后要跳转的链接所需的参数签名
		Sha1Util sh=new Sha1Util();
		SortedMap<String, String> packageParams = new TreeMap<String, String>();
		packageParams.put("userId", userId);  
		packageParams.put("orderNo", orderNo);   
		packageParams.put("money", money); 
		packageParams.put("submchid", subMchid); 
		packageParams.put("notifyUrl", notifyUrl);
		packageParams.put("appid", appid);
		packageParams.put("backurl", backurl);
		packageParams.put("appsecret", appsecret);
		try {
			String selfSign = sh.createSHA1Sign(packageParams);
			logger.info("我方签名:"+selfSign+"\n第三方签名："+sign);
			if(sign.equals(selfSign)){
				//scope 参数视各自需求而定，这里用scope=snsapi_base 不弹出授权页面直接授权目的只获取统一支付接口的openid
				String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
						"appid=" + appid+
						"&redirect_uri=" +
						 backUri+
						"&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
				//九院使用
//				url = WeChatConfig.OAUTH_URL+"?RedirectUri="+backUri;
				System.out.println("url="+url);
				logger.info("普通商户:"+"公众号"+appid+"(公众号ID)"+"的订单"+orderNo+"(订单号)"+"授权成功！url="+url);
				response.sendRedirect(url);
			}else{
				System.out.println("userId="+userId);
				System.out.println("orderNo="+orderNo);
				System.out.println("money="+money);
				System.out.println("subMchid="+subMchid);
				System.out.println("notifyUrl="+notifyUrl);
				System.out.println("backurl="+backurl);
				System.out.println("sign="+sign);
				System.out.println("Sign="+sh.createSHA1Sign(packageParams));
				System.out.println("普通商户:"+"公众号"+"(公众号ID)"+appid+"签名错误!");
				
				logger.info("sign="+sign);
				logger.info("Sign="+sh.createSHA1Sign(packageParams));
				logger.info("普通商户:"+"公众号"+"(公众号ID)"+"签名错误!");
				PayMessage message=new PayMessage();
				ObjectMapper obj=new ObjectMapper();
				message.setMessage("签名错误！");
				message.setState("500");
				String re=obj.writeValueAsString(message);//
				response.getWriter().write(re);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
	
	
	
	
}
